import {
    AboutPanelOptionsOptions,
    app,
    BrowserWindow,
    ipcMain,
    Menu,
    MenuItem,
    MenuItemConstructorOptions,
    nativeTheme,
    Tray
} from "electron";
import {appMenus, editContextMenu, trayMenu} from "./menu";
import {getApp, Host, isMac, Settings} from "../common/utils";
import {EventKeys} from "../common/EventKeys";
import  path from "node:path";
import setTouchBar from "./touchbBar";
import {newBrowserWindow} from "./utils";
import remote = require("@electron/remote/main");


let win: BrowserWindow;
let tray: Tray;
let bounceId: number;
const logoPath = {
    'logo': path.resolve(__dirname, "../icons/logo.ico"),
    'white32': path.resolve(__dirname, "../icons/logo-white32.png"),
    'white16': path.resolve(__dirname, "../icons/logo-white16.png"),
    'black16': path.resolve(__dirname, "../icons/logo-black16.png"),
    'white64': path.resolve(__dirname, "../icons/logo-white64.png"),
    'black64': path.resolve(__dirname, "../icons/logo-black64.png"),
    'white512': path.resolve(__dirname, "../icons/logo-white512.png")
};

function initWindow() {
    if (!app.isReady()) return;
    win = newBrowserWindow({
        height: 768, width: 1024,
        minHeight: 600, minWidth: 800,
        icon: logoPath.white512,
        webPreferences: {
            nodeIntegration: true,
            nodeIntegrationInWorker: true,
            nodeIntegrationInSubFrames: true,
            contextIsolation: false,
            enableRemoteModule: true
        },
        show: false,
        backgroundColor: nativeTheme.shouldUseDarkColors ? "black" : "white",
    });
    if (isMac()) {
        app.dock.setIcon(logoPath.white512);
        app.dock.setMenu(appMenus(win).items[1].submenu)
        setTouchBar(win);
    }
    let willQuit = false;
    app.on("before-quit", () => {
        willQuit = true;
    });
    win.on("close", (e) => {
        willQuit || e.preventDefault();
        win.hide();
    });
    win.on("show", setDockOrTaskIcon);
    win.on("hide", setDockOrTaskIcon);
    win.loadURL(`file://${path.resolve(__dirname, '../renderer/index.html')}`).then(() => {
        win.show();
        isMac() && bounceId && app.dock.cancelBounce(bounceId)
    });
    app.setAboutPanelOptions(aboutOption())
}

function aboutOption(): AboutPanelOptionsOptions {
    return {
        applicationName: app.getName(),
        applicationVersion: app.getVersion(),
        version: app.getVersion(),
        iconPath: nativeTheme.shouldUseDarkColors ? logoPath.white64 : logoPath.black64,
        website: "https://gitee.com/iamhefang/mhosts-electron",
        authors: ["iamhefang"]
    };
}

function setApplicationMenu() {
    if (!app.isReady()) return;
    Menu.setApplicationMenu(appMenus());
}

function setDockOrTaskIcon() {
    if (win.isVisible()) {
        win.setSkipTaskbar(false);
        isMac() && getApp().dock.show();
    } else {
        win.setSkipTaskbar(true);
        isMac() && getApp().dock.hide();
    }
}

function setTray(sender: Electron.WebContents, settings?: Settings) {
    tray.setContextMenu(trayMenu(sender, settings, win));
}

function initMessageChannel() {
    if (!app.isReady()) return;
    ipcMain.on(EventKeys.initTrayMenu, (event, settings?: Settings) => {
        setTray(event.sender, settings)
    })
    ipcMain.on(EventKeys.tellMeTheTheme, (event, args) => {
        event.sender.send(EventKeys.themeChange, nativeTheme.shouldUseDarkColors);
        nativeTheme.on("updated", () => {
            event.sender.send(EventKeys.themeChange, nativeTheme.shouldUseDarkColors);
            win.setBackgroundColor(nativeTheme.shouldUseDarkColors ? "black" : "white");
            tray.setImage(nativeTheme.shouldUseDarkColors ? logoPath.white16 : logoPath.black16);
            app.setAboutPanelOptions(aboutOption());
        });
    });
    ipcMain.on(EventKeys.showTreeContextMenu, (event, host: Host) => {
        const menuTemplate: Array<(MenuItemConstructorOptions) | (MenuItem)> = [
            {
                label: host.isActive ? "取消生效" : "应用到系统",
                click: () => {
                    event.sender.send(EventKeys.applyHost, host)
                }
            },
            {
                label: "修改",
                click: () => {
                    event.sender.send(EventKeys.changeHost, host)
                }
            }
        ];
        if (!host.isActive) {
            menuTemplate.push({
                label: "删除",
                click: () => {
                    event.sender.send(EventKeys.deleteHost, host)
                }
            });
        }
        const treeContextMenu = Menu.buildFromTemplate(menuTemplate);
        treeContextMenu.popup({window: win})
    });
    ipcMain.on(EventKeys.showEditorContextMenu, (event, host: Host) => {
        editContextMenu.popup({window: win})
    });
    ipcMain.on(EventKeys.onDragStart, (e, filePath: string) => {
        e.sender.startDrag({
            file: filePath,
            icon: logoPath.white16
        });
    })
}

export default function startApplication() {
    app.whenReady().then(() => {
        remote.initialize();
        console.log(app.getLocale())
        if (isMac()) {
            bounceId = app.dock.bounce("critical");
        }
        tray = new Tray(nativeTheme.shouldUseDarkColors ? logoPath.white16 : logoPath.black16);
        tray.setToolTip(`${app.getName()}-v${app.getVersion()}`);
        setApplicationMenu();
        initWindow();
        initMessageChannel();
    });
}